package com.hxzy.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述
 *
 * @author tonneyyy
 */
@Configuration
@Log4j2
@Order(-1)
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {


    @SneakyThrows
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
    {
        ServerHttpResponse response = exchange.getResponse();

        //请求已经被提交
        if (exchange.getResponse().isCommitted())
        {
            return Mono.error(ex);
        }

        String msg="";

        if (ex instanceof NotFoundException)
        {
            msg = "服务未找到";
        }
        else if (ex instanceof ResponseStatusException)
        {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        }
        else
        {
            msg = "内部服务器错误";
        }

        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

        return  webFluxResponseWriter(response,HttpStatus.OK,msg);
    }



    public   Mono<Void> webFluxResponseWriter(ServerHttpResponse response,  HttpStatus status, String value) throws JsonProcessingException {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE,  MediaType.APPLICATION_JSON_VALUE);

        //输入自定义对角
        R result =R.build(AckCode.FAIL);
        result.setMsg(value.toString());

        //jackson2转换对象
        ObjectMapper  objectMapper=new ObjectMapper();
        String jsonStr=objectMapper.writeValueAsString(result);

        //把字符串包含成 DataBuffer 缓冲数据
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonStr.getBytes());

        return response.writeWith(Mono.just(dataBuffer));
    }

}
